package com.dmai.capacity.platform.gateway.error;

import com.dmai.capacity.platform.common.constant.UaaConstant;
import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.dmai.capacity.platform.common.utils.WebfluxResponseUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.web.server.ServerWebExchange;
import org.zalando.problem.spring.webflux.advice.security.SecurityAdviceTrait;

import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * 异常处理
 */
public class CustomerSecurityProblemSupport implements ServerAuthenticationEntryPoint, ServerAccessDeniedHandler {

    private SecurityAdviceTrait advice;
    private ObjectMapper mapper;

    public CustomerSecurityProblemSupport(final SecurityAdviceTrait advice, final ObjectMapper mapper) {
        this.advice = advice;
        this.mapper = mapper;
    }

    public Mono<Void> commence(final ServerWebExchange exchange, final AuthenticationException e) {
        return WebfluxResponseUtil.responseWrite(exchange, cn.hutool.http.HttpStatus.HTTP_UNAUTHORIZED, ResponseEntity.of(UaaConstant.AUTH_CODE_INVALID_TOKEN, "无效的Access_token", null));
    }

    public Mono<Void> handle(final ServerWebExchange exchange, final AccessDeniedException e) {
        return advice.handleAccessDenied(e, exchange)
                .flatMap(entity -> WebfluxResponseUtil.responseProblem(exchange, (org.springframework.http.ResponseEntity) entity));
    }

}
